<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="配置名称" prop="configName">
        <el-input
          v-model="queryParams.configName"
          placeholder="请输入配置名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="启用" value="1" />
          <el-option label="停用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['device:collect:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['device:collect:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['device:collect:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="collectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="配置ID" align="center" prop="configId" width="80" />
      <el-table-column label="配置名称" align="center" prop="configName" :show-overflow-tooltip="true" />
      <el-table-column label="API地址" align="center" prop="apiUrl" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="采集间隔(秒)" align="center" prop="collectInterval" width="120" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === '1'" type="success">启用</el-tag>
          <el-tag v-else type="info">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="最后采集时间" align="center" prop="lastCollectTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastCollectTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后采集状态" align="center" prop="lastCollectStatus" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.lastCollectStatus === 'SUCCESS'" type="success">成功</el-tag>
          <el-tag v-else-if="scope.row.lastCollectStatus === 'FAILED'" type="danger">失败</el-tag>
          <el-tag v-else type="info">未执行</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="采集统计" align="center" width="200">
        <template slot-scope="scope">
          <span style="color: #67C23A">成功: {{ scope.row.successCollected || 0 }}</span> / 
          <span style="color: #F56C6C">失败: {{ scope.row.failedCollected || 0 }}</span> / 
          <span>总计: {{ scope.row.totalCollected || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === '0'"
            size="mini"
            type="success"
            icon="el-icon-video-play"
            @click="handleStart(scope.row)"
            v-hasPermi="['device:collect:start']"
          >启动</el-button>
          <el-button
            v-else
            size="mini"
            type="warning"
            icon="el-icon-video-pause"
            @click="handleStop(scope.row)"
            v-hasPermi="['device:collect:stop']"
          >停止</el-button>
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-refresh"
            @click="handleExecute(scope.row)"
            v-hasPermi="['device:collect:execute']"
          >执行</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['device:collect:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['device:collect:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备采集配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="配置名称" prop="configName">
          <el-input v-model="form.configName" placeholder="请输入配置名称" />
        </el-form-item>
        <el-form-item label="API地址" prop="apiUrl">
          <el-input v-model="form.apiUrl" placeholder="请输入API地址" />
        </el-form-item>
        <el-form-item label="Authorization" prop="authorization">
          <el-input 
            v-model="form.authorization" 
            type="textarea" 
            :rows="3"
            placeholder="请输入Authorization令牌"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="每页数量" prop="pageSize">
          <el-input-number v-model="form.pageSize" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="采集间隔(秒)" prop="collectInterval">
          <el-input-number v-model="form.collectInterval" :min="10" :max="3600" />
          <span style="color: #909399; font-size: 12px; margin-left: 10px;">建议设置30秒</span>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCollect, getCollect, delCollect, addCollect, updateCollect, startCollect, stopCollect, executeCollect } from "@/api/device/collect";

export default {
  name: "Collect",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备采集配置表格数据
      collectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        configName: null,
        apiUrl: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        configName: [
          { required: true, message: "配置名称不能为空", trigger: "blur" }
        ],
        apiUrl: [
          { required: true, message: "API地址不能为空", trigger: "blur" }
        ],
        authorization: [
          { required: true, message: "Authorization令牌不能为空", trigger: "blur" }
        ],
        pageSize: [
          { required: true, message: "每页数量不能为空", trigger: "blur" }
        ],
        collectInterval: [
          { required: true, message: "采集间隔不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询设备采集配置列表 */
    getList() {
      this.loading = true;
      listCollect(this.queryParams).then(response => {
        this.collectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        configId: null,
        configName: null,
        apiUrl: "https://5g.report.szafx.cn/equipment/list",
        authorization: null,
        pageSize: 10,
        collectInterval: 30,
        status: "0",
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.configId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备采集配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const configId = row.configId || this.ids
      getCollect(configId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备采集配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.configId != null) {
            updateCollect(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCollect(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const configIds = row.configId || this.ids;
      this.$modal.confirm('是否确认删除设备采集配置编号为"' + configIds + '"的数据项？').then(function() {
        return delCollect(configIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 启动任务 */
    handleStart(row) {
      this.$modal.confirm('是否确认启动采集任务"' + row.configName + '"？').then(() => {
        return startCollect(row.configId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("启动成功，请在定时任务中配置调度");
      }).catch(() => {});
    },
    /** 停止任务 */
    handleStop(row) {
      this.$modal.confirm('是否确认停止采集任务"' + row.configName + '"？').then(() => {
        return stopCollect(row.configId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("停止成功");
      }).catch(() => {});
    },
    /** 手动执行采集 */
    handleExecute(row) {
      this.$modal.confirm('是否立即执行一次采集任务"' + row.configName + '"？').then(() => {
        return executeCollect(row.configId);
      }).then(() => {
        this.$modal.msgSuccess("采集任务已提交执行，请稍后查看结果");
        // 3秒后刷新列表
        setTimeout(() => {
          this.getList();
        }, 3000);
      }).catch(() => {});
    }
  }
};
</script>

